#include "tcp.h"

#define CLIENT_IP_CONFIG_FILE ".clientIpInfo"
#define OK '1' 
int main(int argc, char * argv[]){


	int sockfd, fd;
	FILE * fp = fopen(CLIENT_IP_CONFIG_FILE, "r");
	char *ip;
	char *port;
	char *transportFile;
	char buff[BUFSIZ] = {};
	int ret;

	//检查上送参数
	if(argc < 2){
		ErrorExit("arg");
	}
	transportFile = argv[1];

	//读取本地文件配置
	readConfig(buff, fp, &ip, &port);
	printf("%s\n%s\n", ip, port);

	//套接字初始化(客户端)
	sockfd = socketInit(ip, port, false);

	//将文件名发往服务端
	printf("transportFile : %s\n", transportFile);
	socketTransport(sockfd, transportFile, strlen(transportFile), (func_socket_data)write);
	//接收到服务端的确认信号
	socketTransport(sockfd, buff, 1, read);
	
	//打开本地文件
	fd = open(transportFile, O_RDONLY);
	if(fd < 0){
		ErrorExit("open failed\n");
	}

	if(buff[0] == OK){
		while(1){
			//读取本地文件数据到buff中
			ret = socketTransport(fd, buff, BUFSIZ, read);
			if(!ret){
				break;
			}
			//开始传输文件
			//不能使用strlen, 因为\0也是正常的数据
			//socketTransport(sockfd, buff, strlen(buff), (func_socket_data)write);
			socketTransport(sockfd, buff, ret, (func_socket_data)write);
		}
	}

	close(sockfd);
	close(fd);
	fclose(fp);

}
